package com.lu.service;

import com.lu.dao.mapper.BlogMapper;
import com.lu.dao.mapperExt.BlogMapperExt;
import com.lu.dto.BlogDTO;
import com.lu.entity.Blog;
import com.lu.entity.BlogExample;
import com.lu.utils.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lulu on 2017/8/30.
 */
@Service
public class BlogService {
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    BlogMapperExt mapperExt;

    public List<BlogDTO> getBlog(String key) {
        BlogExample example = new BlogExample();
        BlogExample.Criteria cri = example.createCriteria();
        cri.andIsshowEqualTo((byte) 1);

        if (!StringUtils.isEmpty(key) && !key.trim().isEmpty()) {
            cri.andTitleLike("%" + key + "%");
        }

        List<Blog> dataList = blogMapper.selectByExampleWithBLOBs(example);
        if (CollectionUtil.isEmpty(dataList)) {
            return new ArrayList<>(0);
        }

        List<BlogDTO> dtos = new ArrayList<>(dataList.size());

        for (Blog blog : dataList) {
            BlogDTO dto = new BlogDTO();
            BeanUtils.copyProperties(blog, dto);
            dtos.add(dto);
        }

//        int total = dataList.stream().mapToInt(value -> value.getReadcount()).sum();

        return dtos;
    }

    public BlogDTO getBlogById(int id) {
        BlogDTO dto = new BlogDTO();
        Blog blog = blogMapper.selectByPrimaryKey(id);
        if (blog == null) {
            return null;
        }
        BeanUtils.copyProperties(blog, dto);
        mapperExt.addReadCount(id);
        return dto;
    }

    //赞同数加一：
    public void addLikeCount(int id) {
        mapperExt.addlikeCount(id);
    }
}
